package com.example.littleken.musictextend;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.example.littleken.musictextend.config.config;
import com.example.littleken.musictextend.entity.Music;
import com.example.littleken.musictextend.entity.MusicList;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {
    private RelativeLayout root_layout;
    SimpleAdapter simpleAdapter;
    private static final String TAG = "MusicText";
    //上一首歌
    private ImageButton imgBtn_Previous;
    //播放停止按钮
    private ImageButton imgBtn_PlayOrPause;
    //停止
    private ImageButton imgBtn_Stop;
    //下一首歌
    private ImageButton imgBtn_Next;
    //音乐列表listview
    private ListView list;
    //当前播放时间
    private TextView text_Current;
    //歌曲总时长
    private TextView text_Duration;
    //进度条
    private SeekBar seekBar;
    //广播接收器
    private StatusChangedReceiver receiver = null;

    //handle用于控制进度条
    private Handler seekBarHandler;
    //当前歌曲的持续时间和当前位置，作用于进度条

    private int duration;
    private int time;

    //进度条状态
    private static final int PROGRESS_INCREASE = 0;
    private static final int PROGRESS_PAUSE = 1;
    private static final int PROGRESS_RESET = 2;
    //播放媒体类
    private MediaPlayer player = new MediaPlayer();

    //歌曲存放列表
    private ArrayList<Music> musicArrayList;

    // 当前歌曲的序号
    private int number = 0;

    //播放状态
    private int status;
    //动态申请权限
    checkPermissionGranted checkPermissionGranted;

    //默认休眠状态
    private static  boolean sleepmode;
    private int sleepminute =20;
    private static final boolean ISSLEEP =true;
    private Timer timer_sleep;
    private static final boolean NOTSLEEP= false;

    //用于保存主题
    SharedPreferences sharedPreferences ;
    //默认主题
    private String theme = "彩色";
    //保存theme字段
    public static final String THEMEFLAG = "theme";

    private static boolean isExit =false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //动态申请权限
        checkPermissionGranted = new checkPermissionGranted(MainActivity.this,config.permission,config.MY_PERMISSION_REQUEST_CODE,config.checkFailMsg);
        checkPermissionGranted.check();
        //初始化控件
        initView();
        initTheme();
        //初始化监听器
        initListener();
        //初始化音乐列表
        initMusicList();
        //初始化列表
        initListView();
        //确定音乐列表是否为空
        checkMusicfile();
        //初始化播放进度与歌曲时长
        duration=0;
        time=0;
        //绑定广播接收器
        bindStatusChangedReceiver();
        //初始化seekhandler，控制进度条
        initSeekBarHandler();
        //开启服务播放 歌曲
        startService(new Intent(this, MusicService.class));
        status = MusicService.COMMAND_STOP;
    }

    private void initTheme() {
        sharedPreferences = getSharedPreferences(THEMEFLAG, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        //通过判断存储中的信息，来确定app是否第一次启动
        String flag = sharedPreferences.getString(THEMEFLAG,null);
        //Log.e(TAG, "theme "+flag);
        if(flag==null||flag.equals("")){
            editor.putString(THEMEFLAG,theme);
            setTheme(flag);
        }
        setTheme(flag);
    }

    /**
     * 初始化控件
     */
    private void initView() {
        root_layout = (RelativeLayout)findViewById(R.id.root_layout);
        imgBtn_Previous = (ImageButton) findViewById(R.id.imageButton1);
        imgBtn_PlayOrPause = (ImageButton) findViewById(R.id.imageButton2);
        imgBtn_Stop = (ImageButton) findViewById(R.id.imageButton3);
        imgBtn_Next = (ImageButton) findViewById(R.id.imageButton4);
        list = (ListView) findViewById(R.id.listView1);
        seekBar = (SeekBar) findViewById(R.id.seekBar1);
        text_Current = (TextView) findViewById(R.id.textView1);
        text_Duration = (TextView) findViewById(R.id.textView2);
    }

//    private void setTheme(String theme){
//        if (config.Theme_COLOR.equals(theme)) {
//            root_layout.setBackgroundResource(R.drawable.bg_color);
//        } else if (config.Theme_FLOWER.equals(theme)) {
//            root_layout.setBackgroundResource(R.drawable.bg_digit_flower);
//        } else if (config.Theme_MOUNTAIN.equals(theme)) {
//            root_layout.setBackgroundResource(R.drawable.bg_mountain);
//        } else if (config.Theme_DOG.equals(theme)) {
//            root_layout.setBackgroundResource(R.drawable.bg_running_dog);
//        } else if (config.Theme_ICE.equals(theme)) {
//            root_layout.setBackgroundResource(R.drawable.bg_snow);
//        } else if (config.Theme_GIRL.equals(theme)) {
//            root_layout.setBackgroundResource(R.drawable.bg_music_girl);
//        } else if (config.Theme_OBSCURE.equals(theme)) {
//            root_layout.setBackgroundResource(R.drawable.bg_blur);
//        }
//
//    }

    private void setTheme(String theme) {
        if ("彩色".equals(theme)) {
            this.root_layout.setBackgroundResource(R.drawable.bg_color);
        } else if ("花朵".equals(theme)) {
            this.root_layout.setBackgroundResource(R.drawable.bg_digit_flower);
        } else if ("群山".equals(theme)) {
            this.root_layout.setBackgroundResource(R.drawable.bg_mountain);
        } else if ("小狗".equals(theme)) {
            this.root_layout.setBackgroundResource(R.drawable.bg_running_dog);
        } else if ("冰雪".equals(theme)) {
            this.root_layout.setBackgroundResource(R.drawable.bg_snow);
        } else if ("女孩".equals(theme)) {
            this.root_layout.setBackgroundResource(R.drawable.bg_music_girl);
        } else if ("朦胧".equals(theme)) {
            this.root_layout.setBackgroundResource(R.drawable.bg_blur);
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        this.getMenuInflater().inflate(R.menu.main,menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_theme:
                (new AlertDialog.Builder(this)).setTitle("请选择主题").
                        setItems(R.array.theme, new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                        setTheme(config.theme[which]);
                        sharedPreferences = getSharedPreferences(THEMEFLAG, Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putString(THEMEFLAG,config.theme[which]);
                        editor.commit();
                    }
                }).show();
                break;
            case R.id.menu_about:
                (new AlertDialog.Builder(this)).setTitle("MusicText").setMessage(R.string.about2).show();
                break;
            case R.id.menu_time_quit:
                //Toast.makeText(MainActivity.this,"倒计时",Toast.LENGTH_LONG).show();
                showSleepDialog();
                break;
            case R.id.menu_quit:
                //退出程序
                (new AlertDialog.Builder(this)).setTitle("提示").
                        setMessage(R.string.quit).setPositiveButton("确定",
                        new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                        finish();
                    }
                }).setNegativeButton("取消",
                        new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                    }
                }).show();
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 初始化监听器
     */
    private void initListener() {
        //上一首按钮
        imgBtn_Previous.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                //发送消息给service
                sendBroadcastOnCommand(MusicService.COMMAND_PREVIOUS);
            }
        });

        //播放暂停按钮
        imgBtn_PlayOrPause.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                switch (status) {
                    //若正在播放，就暂停
                    case MusicService.STATUS_PLAYING:
                        sendBroadcastOnCommand(MusicService.COMMAND_PAUSE);
                        break;
                    //若暂停就播放
                    case MusicService.STATUS_PAUSED:
                        sendBroadcastOnCommand(MusicService.COMMAND_RESUME);
                        break;
                    //停止就播放
                    case MusicService.COMMAND_STOP:
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                    default:
                        break;
                }
                //Log.e(TAG, "进度" + time );
            }
        });

        //停止按钮
        imgBtn_Stop.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                sendBroadcastOnCommand(MusicService.COMMAND_STOP);
            }
        });

        //下一首按钮
        imgBtn_Next.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
            }
        });

        //播放列表点击监听
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                number = position;
                sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
            }
        });
        list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                //Toast.makeText(MainActivity.this,"长按"+position,Toast.LENGTH_LONG).show();
                new android.app.AlertDialog.Builder(MainActivity.this).setTitle("删除").
                        setNegativeButton("取消",new android.content.DialogInterface.OnClickListener(){

                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).setPositiveButton("确定",new android.content.DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String path = musicArrayList.get(position).getmusicPath();
                         File file = new File(path);
                        file.delete();
                        musicArrayList.remove(position);
                    }
                }).setMessage("是否确定删除").show();
//
                return true;
            }
        });

        //进度条拖动监听
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            //监听停下的位置
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //如果当前播放状态不为停止
                if(status != MusicService.STATUS_STOPPED){
                    time =seekBar.getProgress();
                    text_Current.setText(formatTime(time));
                    //发送广播让service执行跳转
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                }
                if(status == MusicService.STATUS_PLAYING){
                    //发送广播给MusicService，执行跳转
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                    //进度条恢复移动
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE,1000);
                }

            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //进度条暂停移动
                seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);
            }
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }
        });

    }

    /**
     * 初始化音乐列表
     */
    private void initMusicList() {
        musicArrayList = MusicList.getMusicList();
        //列表判空
        if (musicArrayList.isEmpty()) {
            Cursor mMusicCursor = this.getContentResolver().query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
                    MediaStore.Audio.AudioColumns.TITLE);
            //标题
            int indexTitle = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE);
            //艺术家
            int indexArtist = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST);
            //总时长
            int indexTotalTime = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION);
            //路径
            int indexPath = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);

            /**通过mMusicCursor游标遍历数据库，并将Music类对象加载到ArrayList中*/
            for (mMusicCursor.moveToFirst(); !mMusicCursor.isAfterLast(); mMusicCursor
                    .moveToNext()) {
                String strTitle = mMusicCursor.getString(indexTitle);
                String strArtist = mMusicCursor.getString(indexArtist);
                String strTotoalTime = mMusicCursor.getString(indexTotalTime);
                String strPath = mMusicCursor.getString(indexPath);

                if (strArtist.equals("<unknown>")) {
                    strArtist = "无艺术家";
                    Music music = new Music(strTitle, strArtist, strPath, strTotoalTime);
                    musicArrayList.add(music);
                   // Log.e(TAG, music.toString());
                } else {
                    Music music = new Music(strTitle, strArtist, strPath, strTotoalTime);
                    musicArrayList.add(music);
                   // Log.e(TAG, music.toString());
                }

            }
        }

    }

    //绑定广播监听器
    private void bindStatusChangedReceiver() {
        receiver = new StatusChangedReceiver();
        //广播过滤器，只接收service的广播
        IntentFilter filter = new IntentFilter(MusicService.BROADCAST_MUSICSERVICE_UPDATE_STATUS);
        registerReceiver(receiver, filter);
    }

    /**
     * 检查音乐列表是否为空，若为空，禁止按键操作以免报错
     */
    private void checkMusicfile() {
        if (musicArrayList.isEmpty()) {
            // 若播放列表为空，禁止所有按键
            imgBtn_Next.setEnabled(false);
            imgBtn_PlayOrPause.setEnabled(false);
            imgBtn_Previous.setEnabled(false);
            imgBtn_Stop.setEnabled(false);
            Toast.makeText(getApplicationContext(), "当前没有歌曲文件", Toast.LENGTH_LONG).show();
        } else {
            imgBtn_Next.setEnabled(true);
            imgBtn_PlayOrPause.setEnabled(true);
            imgBtn_Previous.setEnabled(true);
            imgBtn_Stop.setEnabled(true);
        }
    }

    //初始化音乐列表
    private void initListView() {
        List<Map<String, String>> list_map = new ArrayList<Map<String, String>>();
        HashMap<String, String> map;
        for (Music music : musicArrayList) {
            map = new HashMap<String, String>();
            map.put("musicName", music.getmusicName());
            map.put("musicArtist", music.getmusicArtist());
            list_map.add(map);
        }

        String[] from = new String[]{"musicName", "musicArtist"};
        int[] to = {R.id.listview_tv_title_item, R.id.listview_tv_artist_item};

        simpleAdapter = new SimpleAdapter(this, list_map, R.layout.listview, from, to);
        list.setAdapter(simpleAdapter);
    }


    /**
     * 通过广播，把指令告知service
     * @param command 操作指令
     */
    private void sendBroadcastOnCommand(int command) {

        Intent intent = new Intent(MusicService.BROADCAST_MUSICSERVICE_CONTROL);
        intent.putExtra("command", command);

        switch (command) {
            //根据指令封装不同信息
            case MusicService.COMMAND_PLAY:
                intent.putExtra("number", number);
                break;
            case MusicService.COMMAND_SEEK_TO:
                intent.putExtra("time",time);
                break;

                //不需要第二信息
            case MusicService.COMMAND_PREVIOUS:
            case MusicService.COMMAND_NEXT:
            case MusicService.COMMAND_PAUSE:
            case MusicService.COMMAND_STOP:
            case MusicService.COMMAND_RESUME:
            default:
                break;
        }
        sendBroadcast(intent);
    }

    //初始化seekBarHandler 用于控制进度条
    private void initSeekBarHandler() {
        seekBarHandler = new Handler() {
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case PROGRESS_INCREASE:
                        if (seekBar.getProgress() < duration) {
                            //进度条前进一秒
                            seekBar.setProgress(time);
                            seekBar.incrementProgressBy(1000);
                            seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                            //修改显示当前进度的文本
                            text_Current.setText(formatTime(time));
                            time += 1000;
                        }
                        break;
                    case PROGRESS_PAUSE:
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        break;
                    case PROGRESS_RESET:
                        //重置进度条画面
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        seekBar.setProgress(0);
                        text_Current.setText("00:00");
                        break;
                }
            }
        };
    }
    /**
     * 格式化时间
     * @param msec
     * @return
     */
    private String formatTime(int msec) {
        int minute = msec / 1000 / 60;
        int second = msec / 1000 % 60;
        String minuteString;
        String secondString;
        if (minute < 10) {
            minuteString = "0" + minute;
        } else {
            minuteString = "" + minute;
        }
        if (second < 10) {
            secondString = "0" + second;
        } else {
            secondString = "" + second;
        }
        return minuteString + ":" + secondString;
    }

//广播接收器内，用于处理servier返回的 广播信息
    class StatusChangedReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            //获取播放器状态
            status = intent.getIntExtra("status", -1);
            switch (status) {
                case MusicService.STATUS_PLAYING:
                    String musicName = intent.getStringExtra("musicName");
                    String musicAritist = intent.getStringExtra("musicAritist");
                    seekBarHandler.removeMessages(PROGRESS_INCREASE);
                    time = intent.getIntExtra("time", 0);
                    duration = intent.getIntExtra("duration", 0);
                    number = intent.getIntExtra("number", number);
                    list.setSelection(number);
                    seekBar.setProgress(time);
                    seekBar.setMax(duration);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                    text_Duration.setText(formatTime(duration));
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.pause);
                    //设置textview文字，提示已经播放的歌曲
                    MainActivity.this.setTitle("正在播放:" + musicName + " - " + musicAritist);
                    break;
                case MusicService.STATUS_PAUSED:
                    seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.play);
                    String string = MainActivity.this.getTitle().toString().replace("正在播放", "已暂停");
                    MainActivity.this.setTitle(string);
                    break;
                case MusicService.STATUS_STOPPED:
                    time = 0;
                    duration = 0;
                    text_Current.setText(formatTime(time));
                    text_Duration.setText(formatTime(duration));
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    MainActivity.this.setTitle("MusicText");
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.play);
                    break;
                    //列表最后一首
                case MusicService.STATUS_COMPLETED:
                    number = intent.getIntExtra("number", 0);
                    if (number == MusicList.getMusicList().size() - 1)
                        sendBroadcastOnCommand(MusicService.STATUS_STOPPED);
                    else
                        sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    MainActivity.this.setTitle("MusicText");
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.play);
                    break;
                default:
                    break;
            }
        }
    }
    private void showSleepDialog() {
        //获取布局
        final View tagview = this.getLayoutInflater().inflate(R.layout.dialog, null);

        //通过View类的findViewById方法获取到组件对象
        final TextView tv_minute = (TextView)tagview.findViewById(R.id.dialog_tv);
        final Switch switch1 = (Switch)tagview.findViewById(R.id.dialog_switch);
        final SeekBar seekbar = (SeekBar)tagview.findViewById(R.id.dialog_seekbar);

        tv_minute.setText("睡眠于:"+sleepminute+"分钟");
        //根据当前的睡眠状态来确定Switch的状态
        if(sleepmode == MainActivity.ISSLEEP) {
            switch1.setChecked(true);
        }

        seekbar.setMax(60);
        seekbar.setProgress(sleepminute);
        seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar arg0) {
            }
            @Override
            public void onStartTrackingTouch(SeekBar arg0) {
            }
            @Override
            public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
                sleepminute = arg1;
                tv_minute.setText("睡眠于:"+sleepminute+"分钟");

            }
        });
        switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                sleepmode = arg1;
            }
        });
        //定义定时器任务
        final TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                System.exit(0);
            }
        };
        //定义对话框以及初始化
        final android.app.AlertDialog.Builder dialog = new android.app.AlertDialog.Builder(this);
        dialog.setTitle("选择睡眠时间(0~60分钟)");
        //设置布局
        dialog.setView(tagview);
        //设置取消按钮响应事件
        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                arg0.dismiss();
            }
        });
        //设置重置按钮响应时间
        dialog.setNeutralButton("重置", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                if(sleepmode == MainActivity.ISSLEEP)
                {
                    timerTask.cancel();
                    timer_sleep.cancel();
                }
                sleepmode = MainActivity.NOTSLEEP;
                sleepminute = 20;
            }
        });
        //设置确定按钮响应事件
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {

                if(sleepmode == MainActivity.ISSLEEP) {
                    timer_sleep = new Timer();
                    int time =seekbar.getProgress();
                    //启动任务，time*60*1000毫秒后执行
                    timer_sleep.schedule(timerTask, time*60*1000);
                }
                else
                {
                    //取消任务
                    timerTask.cancel();
                    if(timer_sleep != null) timer_sleep.cancel();
                    arg0.dismiss();
                }
            }
        });

        dialog.show();
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        checkPermissionGranted.onRequestPermissionsResult(requestCode,permissions,grantResults);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (status == MusicService.STATUS_STOPPED) {
            stopService(new Intent(this, MusicService.class));
        }
        if(receiver != null){
            unregisterReceiver(receiver);
        }
    }
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode){
            case KeyEvent.KEYCODE_BACK:
                exitByDoubleClick();
                break;
        }
        return false;
    }
    private void exitByDoubleClick(){
        Timer timer = null;
        if(isExit == false) {
            isExit = true;
            Toast.makeText(this, "再按一次退出程序！", Toast.LENGTH_LONG).show();
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;
                }
            }, 2000);
        }
        else {
            finish();
        }
    }
}
